'ODM Tools
'Copyright (c) 2007, Utah State University
'All rights reserved.
'Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
'*           Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
'*           Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
'*           Neither the name of the Utah State University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Imports System.Windows.Forms
Imports Odm.Data.Common

Public Class frmAddNewValue

    'Last Documented 5/15/07

#Region " Member Variables "
    Private m_QualifierCreateNew As Odm.Data.Model.Qualifier = New Odm.Data.Model.Qualifier() With {.ID = -1, .Code = "<Create New>"} 'Place holder in item picker
    Private m_QualifierNone As Odm.Data.Model.Qualifier = New Odm.Data.Model.Qualifier() With {.ID = -1, .Code = "<None>"} 'Place holder in item picker
    Private m_SampleNone As Odm.Data.Model.Sample = New Odm.Data.Model.Sample() With {.ID = -1, .LaboratoryCode = "<None>"} 'Place holder in item picker
    Private Const m_NoCensor As String = "nc" 'Default Censor Code value

    Friend m_DataValue As Odm.Data.Model.DataValue

#End Region

#Region " Form Control Functions "

    Public Sub New()
        InitializeComponent()

        m_DataValue = New Odm.Data.Model.DataValue() _
            With _
            { _
                .OffsetType = New Odm.Data.Model.OffsetType() With {.ID = -1, .Description = "<None>", _ 
                .Unit = New Odm.Data.Model.Unit() With {.ID = -1, .Name = "<None>"}} _
            }
    End Sub

    Public Sub New(ByVal e_OffsetType As Odm.Data.Model.OffsetType)
        'Input:     e_offsetType -> The Offset type for the new point
        '           e_offsetunits -> The Offset units for the new point

        Me.New()

        ' This call is required by the Windows Form Designer.
        If Not e_OffsetType Is Nothing Then
            m_DataValue.OffsetType = e_OffsetType
        End If

    End Sub

    Private Sub frmAddNewValue_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Sets all the Default Values and Information
        'Loads lists of qualifiers, censorcodes, and samples

        dtpANVDateTime.Value = Now
        dtpANVDateTime.MaxDate = Now.AddMonths(1)
        cboANVUtcOffset.Text = (Now - Date.UtcNow).TotalHours
        txtANVOffsetType.Text = m_DataValue.OffsetType.Description
        If m_DataValue.OffsetType.ID < 0 Then
            txtANVOffsetValue.Enabled = False
        Else
            txtANVOffsetValue.Enabled = True
            txtANVOffsetUnits.Text = m_DataValue.OffsetType.Unit.Name
        End If

        LoadQualifiers()
        LoadCensorCodes()
        LoadSamples()
    End Sub

    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
        'Checks if data is all valid then returns it to the calling form
        'Output:    Pops up a message box if there is a problem with the data
        '           The form returns dialogresult.ok if everything is correct
        Try
            If Not (IsNumeric(txtANVDataValue.Text)) Then
                ShowError("Please enter a valid numeric value for the Data Value.")
            ElseIf (m_DataValue.OffsetType.ID >= 0) And (Not IsNumeric(txtANVOffsetValue.Text)) Then
                ShowError("Please enter a valid numeric value for the Offset Value.")
            ElseIf (cboANVQualifier.SelectedIndex < 0) Then
                ShowError("Please select/create a Qualifier.", New Exception)
            ElseIf (cboANVCensorCode.SelectedIndex < 0) Then
                ShowError("Please select a Censor Code.  Default is 'nc' for Not Censored.")
            ElseIf (cboANVUtcOffset.SelectedIndex < 0) Then
                ShowError("Please select the UTC Offset (Add 1 for DST).")
            ElseIf (cboANVSample.SelectedIndex < 0) Then
                ShowError("Please select a Sample.  Default if '<None>' if data did not come from a sample.")
            Else
                m_DataValue.Value = CDbl(txtANVDataValue.Text)
                m_DataValue.Qualifier = cboANVQualifier.SelectedItem
                If m_DataValue.Qualifier.ID < 0
                    m_DataValue.Qualifier = Nothing
                End If

                Dim censorCode As Odm.Data.Model.Term = cboANVCensorCode.SelectedItem
                m_DataValue.CensorCode = censorCode.Name

                m_DataValue.DateTime = dtpANVDateTime.Value
                m_DataValue.UTCOffset = cboANVUtcOffset.SelectedItem

                m_DataValue.Sample = cboANVSample.SelectedItem
                If m_DataValue.Sample.ID < 0
                    m_DataValue.Sample = Nothing
                End If

                If txtANVOffsetValue.Text <> "" Then m_DataValue.OffsetValue = CDbl(txtANVOffsetValue.Text)

                Me.DialogResult = System.Windows.Forms.DialogResult.OK
                Me.Close()
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        'Closes the form and returns a cancel to the calling form  
        'Output:   Returns dialogResult.cancel 
        Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

    Private Sub dtpANVDateTime_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpANVDateTime.ValueChanged
        'When the DT value is changed, it updates the UTCDT text
        If cboANVUtcOffset.Text <> "" Then
            Dim utcDateTime As Date 'Used to format the UTC date time
            utcDateTime = dtpANVDateTime.Value.AddHours(-Val(cboANVUtcOffset.SelectedItem))
            txtANVUtcDateTime.Text = utcDateTime.ToString
        End If
    End Sub

    Private Sub cboANVUtcOffset_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboANVUtcOffset.SelectedIndexChanged
        'When the UTC Offset value is changed it updates the UTCDT Text
        If cboANVUtcOffset.Text <> "" Then
            Dim utcDateTime As Date 'Used to format the utc Date Time
            utcDateTime = dtpANVDateTime.Value.AddHours(-Val(cboANVUtcOffset.SelectedItem))
            txtANVUtcDateTime.Text = utcDateTime.ToString
        End If
    End Sub

    Private Sub cboANVQualifier_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboANVQualifier.SelectedIndexChanged
        'If m_CreateNew was selected, then create a new qualifier
        Try
            '1. See if m_CreateNew item = selected            
            If cboANVQualifier.SelectedItem = m_QualifierCreateNew Then
                'show Create Qualifier form
                Dim newQlfy As New frmCreateNewQualifier 'Form for creating the new qualifier
                newQlfy.Owner = Me
                If newQlfy.ShowDialog = Windows.Forms.DialogResult.OK Then
                    'reload Qualifiers, select one just created
                    LoadQualifiers()
                    cboANVQualifier.SelectedItem = newQlfy.m_Qualifier
                End If

                'release resources
                newQlfy = Nothing
            End If

            '2. enable OK Button
            btnOK.Enabled = True

        Catch ex As Exception
            ShowError("An Error occured when a new Qualifier was selected when Flagging Values." & vbCrLf & "Message = " & ex.Message, New Exception)
        End Try
    End Sub

    Private Sub txtANVOffsetValue_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtANVOffsetValue.TextChanged
        'Check if the text is a valid numerical expression, or part of one
        'Output:    Removes any invalid characters
        If (Not IsNumeric(txtANVDataValue.Text)) And (Not txtANVDataValue.Text = "-") And (Not txtANVDataValue.Text = "+") And (Not txtANVDataValue.Text = ".") Then
            Dim i As Integer 'counter variable
            i = txtANVDataValue.SelectionStart - System.Text.RegularExpressions.Regex.Matches(txtANVDataValue.Text, g_NumericExpressionPatern).Count
            If i <= 0 Then i = 1
            txtANVDataValue.Text = System.Text.RegularExpressions.Regex.Replace(txtANVDataValue.Text, g_NumericExpressionPatern, "")
            txtANVDataValue.Select(i, 0)
        End If
    End Sub

    Private Sub txtANVDataValue_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtANVDataValue.TextChanged
        'Check if the text is a valid numerical expression, or part of one
        'Output:    Removes any invalid characters
        If System.Text.RegularExpressions.Regex.Match(txtANVDataValue.Text, g_NumericExpressionPatern).Success Then
            Dim i As Integer 'counter variable
            i = txtANVDataValue.SelectionStart - System.Text.RegularExpressions.Regex.Matches(txtANVDataValue.Text, g_NumericExpressionPatern).Count
            If i <= 0 Then i = 1
            txtANVDataValue.Text = System.Text.RegularExpressions.Regex.Replace(txtANVDataValue.Text, g_NumericExpressionPatern, "")
            txtANVDataValue.Select(i, 0)
        End If
    End Sub

#End Region

#Region " Loading Functions "

    Private Sub LoadQualifiers()
        'Loads all Qualifiers   
        'Output:    Puts the qualifiers into a ComboBox
        Try
            Dim qualifiers As IEnumerable(Of Odm.Data.Model.Qualifier) = g_CurrDataSource.GetQualifiers

            cboANVQualifier.Items.Add(m_QualifierNone)

            For Each qualifier In qualifiers
                cboANVQualifier.Items.Add(qualifier)
            Next
            cboANVQualifier.Items.Add(m_QualifierCreateNew)

            '4. Select first one in list as default
            cboANVQualifier.SelectedIndex = 0

        Catch ex As Exception
            ShowError("An Error occurred while loading the Qualifiers list." & vbCrLf & "Message = " & ex.Message, ex)
        End Try
    End Sub

    Private Sub LoadCensorCodes()
        'Loads all CensorCodes   
        'Output:    Puts the censorcodes into a ComboBox   
        Try
            Dim censorCodes As IEnumerable(Of Odm.Data.Model.Term) = g_CurrDataSource.GetTerms(TermType.CensorCode)

            For Each censorCode In censorCodes
                cboANVCensorCode.Items.Add(censorCode)
                If censorCode.Name = m_NoCensor Then
                    cboANVCensorCode.SelectedItem = censorCode
                End If
            Next

        Catch ex As Exception
            ShowError("An Error occurred while loading the Censor Codes list." & vbCrLf & "Message = " & ex.Message, ex)
        End Try
    End Sub

    Private Sub LoadSamples()
        'Loads all Samples
        'Output:    Puts the Samples into a ComboBox   
        Try

            Dim samples As IEnumerable(Of Odm.Data.Model.Sample) = g_CurrDataSource.GetSamples

            'Create an empty Sample
            cboANVSample.Items.Add(m_SampleNone)

            For Each sample In samples
                cboANVSample.Items.Add(sample)
            Next

            '4. Select first one in list as default
            cboANVSample.SelectedIndex = 0

        Catch ex As Exception
            ShowError("An Error occurred while loading the Samples list." & vbCrLf & "Message = " & ex.Message, ex)
        End Try
    End Sub

#End Region

End Class
